package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Nota;
import model.Student;

/**
 * Servlet implementation class MainServlet
 */
@WebServlet(urlPatterns = "/MainServlet", name = "MainServlet", asyncSupported = true)
public class MainServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	EntityManagerFactory emf;
	EntityManager em;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MainServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	public void init() {

		emf = Persistence.createEntityManagerFactory("ServletTest");
		em = emf.createEntityManager();

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		PrintWriter out = response.getWriter();

		List<Student> studs = em.createQuery("select s from Student s",
				Student.class).getResultList();

		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
				+ "Transitional//EN\">");

		out.println("<html>");

		out.println("<head>");
		out.println("<title>" + "Main page!" + "</title>");
		out.println("</head>");
		out.println("<body bgcolor=\"#F3FBFE\">");
		out.println("<br>");
		out.println("Alege un student");
		out.println("<form method=\"GET\" action=\"/ServletTest/ChoiceServlet\">");
		out.println("<select name=\"studIndex\">");
		for (Student temp : studs) {
			out.println("<option value=\"" + temp.getNume() + "\">"
					+ temp.getNume() + "</option> ");
		}
		out.println("</select>");
		out.println("<input type=\"submit\" value=\"Ok\"></form>");
		out.println("</body>");
		out.println("</html>");

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doGet(request, response);
	}

}
